# coding: utf-8
import requests as r
import os
import json
import datetime


class BilibiliAPI(object):
    def __init__(self, cookie_path=None):
        self.history = None
        self.history_url = 'http://api.bilibili.com/x/web-interface/history/cursor'
        # get the cookie path
        dotfiles_dir = os.getenv('DOTFILES')
        if cookie_path is None:
            cookie_items = os.listdir(os.path.join(dotfiles_dir, 'secret', 'bilibili'))
            if len(cookie_items) == 0:
                raise Exception('Could not find cookie files')
            cookie_path = cookie_items[-1]
        self.cookie_path = os.path.join(dotfiles_dir, 'secret', 'bilibili', cookie_path)
        print(self.cookie_path)
        ## get the cookie
        with open(self.cookie_path, encoding='utf-8') as fp:
            sentences = fp.read().split(';')
            cookie = {s.split('=')[0].strip(): s.split('=')[1].strip() for s in sentences}
        self.cookie = {
            'SESSDATA': cookie['SESSDATA'],
            'bili_jct': cookie['bili_jct']
        }
        print(self.cookie)


    def get_history(self, payload=None):
        if payload is None:
            resp = r.get(self.history_url, cookies=self.cookie).json()
        else:
            resp = r.get(self.history_url, params=payload, cookies=self.cookie).json()
        if resp['code'] != 0:
            raise Exception('Error: %s' % str(resp['code']) + ' ' + resp['message'])
        return resp


    def get_today_history(self, today=datetime.date.today()):
        history = self.get_history()['data']['list']
        self.history = []
        while datetime.date.fromtimestamp(history[-1]['view_at']) == today:
            self.history.extend(history)
            payload = {'view_at': history[-1]['view_at']}
            history = self.get_history(payload=payload)['data']['list']
        self.history.extend([h for h in history if datetime.date.fromtimestamp(h['view_at']) == today])
        with open('output.json', 'w', encoding='utf-8') as fw:
            json.dump(self.history, fw)
        return self.history


    def load_history(self):
        if self.history:
            return self.history
        # try to load history from file
        if os.path.exists('output.json'):
            with open('output.json', encoding='utf-8') as f:
                data = json.load(f)
            # print(data)
            return data
        else:
            self.get_today_history()
            return self.history


if __name__ == "__main__":
    ba = BilibiliAPI()
    print(ba.get_today_history())
    # print(ba.get_today_history(today=datetime.date.today()-datetime.timedelta(days=1)))
